package com.b.Receive;

import com.b.dao.SeckillActivityMapper;
import com.b.domain.SeckillActivity;
import com.b.repository.SeckillActivityRepository;
import jakarta.annotation.Resource;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class StockReceive {
    @Resource
    private SeckillActivityRepository seckillActivityRepository;
    @Resource
    private SeckillActivityMapper seckillActivityMapper;
    @RabbitListener(queues = "stock")
    @Transactional
    public void process(Integer productId){
        System.out.println("收到消息：" + productId);
        Optional<SeckillActivity> seckillActivityOptional = seckillActivityRepository.findByProductId(productId);
        seckillActivityOptional.ifPresent(seckillActivity -> {
            Integer totalStock = seckillActivity.getTotalStock();
            if (totalStock > 0) {
                seckillActivity.setTotalStock(totalStock - 1);
                seckillActivityMapper.updateByPrimaryKey(seckillActivity);
                seckillActivityRepository.save(seckillActivity);
            }
        });
    }
}
